import type { MouseEvent as ReactMouseEvent } from 'react'

export function useDragWindow (type: WindowType) {
  let offsetX = 0
  let offsetY = 0

  function startDragWindow (e: ReactMouseEvent) {
    e.preventDefault()

    offsetX = e.screenX
    offsetY = e.screenY

    document.addEventListener('mousemove', handleMousemove)
    document.addEventListener('mouseup', handleMouseup)
  }
  function handleMousemove (e: MouseEvent) {
    const deltaX = e.screenX - offsetX
    const deltaY = e.screenY - offsetY

    window.api.dragWindow(type, deltaX, deltaY)

    offsetX += deltaX
    offsetY += deltaY
  }
  function handleMouseup () {
    document.removeEventListener('mousemove', handleMousemove)
    document.removeEventListener('mouseup', handleMouseup)
  }

  return {
    startDragWindow,
  }
}